import { createSlice } from '@reduxjs/toolkit'
import { getToken,setToken as _setToken } from '@/utils'
import { message } from 'antd'
import { getUserApi, loginApi } from '@/apis/user'

const TOKENKEY='token_key'
const USERKEY="userInfo_key"
const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        token: getToken(TOKENKEY)||'',
        userInfo:getToken(USERKEY)||''
    },
    // 同步修改方法
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            _setToken(TOKENKEY,action.payload)
        },
        setUserInfo(state,action){
            state.userInfo=action.payload
            _setToken(USERKEY,action.payload)
        }
    }
})
// 解构 actioncreate
const { setToken,setUserInfo } = userStore.actions
// 获取reducer函数
const userReducer = userStore.reducer
// 异步方法
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        try {
            // 发送请求
            const res = await loginApi(loginForm)
           if(res?.data.code==200){
                dispatch(setToken(res.data.data))
                return  Promise.resolve(true)
           }else{
                message.warning(`登录失败,${res.data.message}`)
               return Promise.reject(false)
           }
        } catch (error) {
            console.log(error);
        }
    }
}
// 获取用户信息
const fetchGetUserInfo=()=>{
    return async (dispatch)=>{
        try {
            const res=await getUserApi()
            if(res?.data.code==200){
                dispatch(setUserInfo(JSON.stringify(res.data.data)))
                return  Promise.resolve(true)
           }else{
                message.warning(`失败,${res.data.message}`)
               return Promise.reject(false)
           }
        } catch (error) {
            console.log(error);
        }
    }
}
// 获取用户路由信息

export { setToken,setUserInfo, fetchLogin,fetchGetUserInfo }
export default userReducer